/*
 * Copyright (c) 2008-2009, Computational Crawling LP
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 *    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *    * Neither the name of Computational Crawling LP, 80legs, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.eightylegs.customer.sample;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import com.eightylegs.customer.Default80AppPropertyKeys;
import com.eightylegs.customer.I80App;

/**
 * Class Sample80App.
 * 
 * In the example code below, we are finding all .html 
 * pages on www.techcrunch.com that mention "80legs" or "80 legs". 
 */
public class Sample80App implements I80App {
	private double MAX_WIDTH;
	private double MAX_HEIGHT;
	
	private static final String REGEX_PARSE_LINKS = "((?i)((href)|(HREF))\\s*=\\s*[\"'](.+?)[\"'])|((?i)((src)|(SRC))\\s*=\\s*[\"'](.+?)[\"'])|((?i)<((meta)|(META))\\s*((http)|(HTTP))-((equiv)|(EQUIV))\\s*=\\s*[\"']\\s*((refresh)|(REFRESH))\\s*[\"'].*>)";

	public String getVersion() {
		return "80App_1.2";  // this must be set correctly or 80legs will not use your jar.
	}
	
	public void initialize( Properties properties, byte[] data ) {
		//Data is in form of w,h
		try {
			String inputDataString = byteArrayToString(data, 0, data.length);
			String[] dataStrings = inputDataString.split(",");

			MAX_WIDTH = (double) Integer.parseInt(dataStrings[0]);
			MAX_HEIGHT = (double) Integer.parseInt(dataStrings[1]);
		}
		catch ( Exception e ) {
		}
	}
	
	public Collection<String> parseLinks(byte[] documentContent, String url, Map<String, String> headers, Map<Default80AppPropertyKeys, Object> default80AppProperties, String statusCodeLine) {
/*
		boolean doProcess = false;
		
		for (String key : headers.keySet()) {
			if (key.toLowerCase().equals("content-type")) {
				String mimeType = headers.get(key);
				if (mimeType.contains("image/")) {
					doProcess = true;
				}
				break;
			}
		}

		if (!doProcess) {
			HashSet<String> outlinkSet = new HashSet<String>();
			
			try {
				String pageContents = new String (documentContent, 0, documentContent.length, "UTF-8");
				try {
					URL urlObj = new URL(url);

					Pattern p = Pattern.compile(REGEX_PARSE_LINKS);
					Matcher m = p.matcher(pageContents);
					while (m.find()) {	
						String outLink =  URLFunctions.preProcessURL(m.group(), urlObj, urlObj, true);

						if (!outLink.equals("") && !outlinkSet.contains(outLink)) {
							outlinkSet.add(outLink);
						}	
					}
				} catch (MalformedURLException ex) { }
			} catch (Exception e) { }
		
			return outlinkSet;	
		}
	*/	
		return null;
	}

	public byte[] processDocument(byte[] documentContent, String url, Map<String, String> headers, Map<Default80AppPropertyKeys, Object> default80AppProperties, String statusCodeLine) {

		boolean doProcess = false;
		String imageType = "";
		
		for (String key : headers.keySet()) {
			if (key.toLowerCase().equals("content-type")) {
				String mimeType = headers.get(key);
				if (mimeType.contains("image/")) {
					String[] temp = mimeType.split("/");
					if (temp.length > 1) {
						imageType = temp[1];
					}
					doProcess = true;
				}
				break;
			}
		}
		
		if (doProcess == true) {
			Image curImage = Toolkit.getDefaultToolkit().createImage(documentContent);
			new ImageIcon(curImage); //Make Toolkit load image so W and H are available
		 
			double width = curImage.getWidth(null);
			double height = curImage.getHeight(null);
			
			//System.out.println(url + ", W=" + width);
			//System.out.println(url + ", H=" + height);
			
			if (width > MAX_WIDTH || height > MAX_HEIGHT) {
				double new_width = width;
				double new_height = height;
				
				if (width > MAX_WIDTH) {
					double width_ratio = MAX_WIDTH / width;
					new_height = Math.max((height * width_ratio),1);
					new_width = MAX_WIDTH;
					//System.out.println("after width transform:\t" + new_width + "\t" + new_height);
				}
			
				if (new_height > MAX_HEIGHT) {
					double height_ratio = MAX_HEIGHT / height;
					new_width = Math.max((width * height_ratio),1);
					new_height= MAX_HEIGHT;
					//System.out.println("after height transform:\t" + new_width + "\t" + new_height);
				}
				
				int scaled_width = (int)Math.round(new_width);
				int scaled_height = (int)Math.round(new_height);
				
				Image newImage = curImage.getScaledInstance(scaled_width, scaled_height, Image.SCALE_DEFAULT);
				new ImageIcon(newImage); //Make W and H available
				try {
					BufferedImage bufferedImage = new BufferedImage(scaled_width, scaled_height, BufferedImage.TYPE_INT_RGB);
					Graphics2D g2d = bufferedImage.createGraphics();
			        g2d.drawImage(newImage, null, null);
			        			        
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
				    ImageIO.write(bufferedImage, imageType, baos);
				    baos.flush();
				    byte[] result = baos.toByteArray();
				    baos.close();
				    
				    return result;
				}
				catch (IOException ioe) {
					ioe.printStackTrace();
				}
			} else {
				new ImageIcon(curImage); //Make W and H available
				try {
					//Convert Image object to byte[]
					BufferedImage bufferedImage = new BufferedImage((int)width, (int)height, BufferedImage.TYPE_INT_RGB);
					Graphics2D g2d = bufferedImage.createGraphics();
			        g2d.drawImage(curImage, null, null);
			        
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
				    ImageIO.write(bufferedImage, imageType, baos);
				    baos.flush();
				    
				    byte[] result = baos.toByteArray();
				    baos.close();
				    
				    return result;
				}
				catch (IOException ioe) {
					ioe.printStackTrace();
				}				
			}
		}
		
		return null;
	}
	
	public static String byteArrayToString(byte[] b, int byteStart, int numBytes) throws Exception
	{
		return new String (b, byteStart, numBytes, "UTF-8");
	}
		
}
